package com.rchat.pocmini.wxapi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by ljd on 2017/2/13.
 *
 * http请求工具类
 */

public class HttpUtil {

    public static final String HTTP_POST = "POST";
    public static final String HTTP_GET = "GET";
    public static final String HTTP_PUT = "PUT";
    public static final String HTTP_DELETE = "DELETE";

    /**
     * http访问
     * @param urlStr 访问的url
     * @param requestJson 参数json格式的String
     * @param method post，get，etc
     * @return
     * @throws IOException
     */
    public static String httpConnect(String urlStr, String requestJson,String method) throws IOException {
        //建立连接
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(method);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.connect();
//        Log.e("response code",conn.getResponseCode() + "");
        if(null != requestJson && "".equals(requestJson)){
            OutputStream outputStream = conn.getOutputStream();
            //注意编码格式
            outputStream.write(requestJson.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }
        InputStream inputStream = conn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        StringBuffer buffer = new StringBuffer();
        while ((str = bufferedReader.readLine())!=null) {
            buffer.append(str);
        }
        //释放资源
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        conn.disconnect();
        return buffer.toString();
    }
}
